
package me.module.toolMain
{
	import com.adobe.images.PNGEncoder;
	import com.zero.framework.interfaces.INotification;
	import com.zero.framework.interfaces.INotifyResponder;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import me.common.AppFacade;
	import me.common.Common;
	import me.common.GlobalCore;
	import me.common.res.GameLoader;
	import me.common.resource.ResType;
	import me.common.resource.Resource;
	import me.module.alert.Alert;
	import me.notification.MainNotification;
	import me.utils.NumberTool;
	import me.utils.OpenFile;
	import me.vo.ActionVO;
	
	
	/**
	 * @author 缺硒
	 */
	public class MainModel implements INotifyResponder
	{
		private static var __instance:MainModel;
		
		private var _count:int = 0;
		
		//原精灵的大小
		private var _preWidth:int = 160;
		private var _preHeight:int = 160;
		
		//精灵的大小
		private var _spriteWidth:int;
		private var _spriteHeight:int;
		
		private var _offsetX:Number;
		private var _offsetY:Number;
		
		private var _runPath:String;
		private var _waitPath:String;
		private var _dazuoPath:String;
		private var _spriteDic:Dictionary;
		
		private var _theABitmapdata:BitmapData;
		private var _theBBitmapdata:BitmapData;
		private var _actionList:Array;
		private var _rootFile:File;
		
		private var _totalCount:int = 0;
		
		private var _fucking1:ByteArray;
		private var _fucking2:ByteArray;
		private var _fucking3:ByteArray;
		private var _fucking4:ByteArray;
		
		private var _isHaveBack:Boolean = true;
		
		public static function getInstance():MainModel
		{
			if(__instance == null)
				__instance = new MainModel(new Singleton());
			return __instance;
		}
		
		// 构造函数
		public function MainModel(s:Singleton)
		{
			AppFacade.getInstance().registerResponder(this);
			
			
		}
		
		
		
		public function get notificationList():Array
		{
			return [
				MainNotification.UI_CLICK_FIND_PATH,
				MainNotification.UI_SET_SPRITE_SIZE,
				MainNotification.UI_OUT_PUT
			];
		}
		
		public function notifyHandler(notification:INotification):void
		{
			var body:Object = notification.getBody();
			switch(notification.getName())
			{
				case MainNotification.UI_CLICK_FIND_PATH:
					OpenFile.browseForDirectory(onc);
					break;
				
				case MainNotification.UI_SET_SPRITE_SIZE:
					_spriteWidth 	= body.w;
					_spriteHeight 	= body.h;
					break;
				
				case MainNotification.UI_OUT_PUT:
					onOutPut(body);
					break;
			}
		}
		
		private function onOutPut(data:Object):void
		{
			_offsetX 		= data.x;
			_offsetY 		= data.y;
			_spriteWidth 	= data.w;
			_spriteHeight	= data.h;
			
			//			stickASprites();
			stickFuckingSprites();
			//			var ba:ByteArray = PNGEncoder.encode(_theABitmapdata);
			//			var file:FileReference = new FileReference();
			//			file.save(ba, GlobalCore.avatarName+".png");
		}
		
		private function onc(file:File):void
		{
			
			_actionList = new Array();
			Resource.getInstance().clearAll();
			GlobalCore.frameNum = 0;
			GlobalCore.totleLine = 0;
			_totalCount = 0;
			if(file != null)
			{
				Alert.showLog("开始加载...");
				_rootFile = file;
				var files:Array =  file.getDirectoryListing();
				for(var i:int = 0; i < files.length; i ++)
				{
					var path:String = files[i].name;
					var strs:Array = path.split("_");
					if(strs.length == 2)
					{
						GlobalCore.avatarName 	= strs[0];
						var action:ActionVO 	= new ActionVO();
						action.name 	= strs[1];
						action.urlPath 	= files[i].nativePath;
						_actionList.push(action);
						//判断文件夹名_后面叫什么名
						//						if(strs[1] == "run01")
						//							_runPath = files[i].nativePath;
						//						if(strs[1] == "stand01")
						//							_waitPath = files[i].nativePath;
						//						if(strs[1] == "dazuo01")
						//							_dazuoPath = files[i].nativePath;
					}
				}
				//				trace(GlobalCore.avatarName, _runPath, _waitPath, _dazuoPath)
				//				loadRunSprites();
				//				_actionList.reverse();
				analyzeAction();
			}
		}
		
		private function analyzeAction():void
		{
			if(_totalCount < _actionList.length)
			{
				var action:ActionVO = _actionList[_totalCount];
				var partPath:String =  GlobalCore.avatarName + "_" + action.name;
				var files:Array = _rootFile.resolvePath(partPath).getDirectoryListing();

				for(var i:int = 0; i < files.length; i ++)
				{
					var file:File = files[i] as File;
					var strs:Array = file.name.split(".");
					if(strs.length == 2 && strs[1] == "png")
					{
						strs = strs[0].split("_");
						if(strs.length == 4)
						{
							if(int(strs[2]) > action.lineNum) action.lineNum = int(strs[2]);
							if(int(strs[3]) > action.frameNum) action.frameNum = int(strs[3]);
							if(action.frameNum > GlobalCore.frameNum) GlobalCore.frameNum = action.frameNum;
						}
					}
				}
				
				for(i = 0; i < action.lineNum; i ++)
				{
					for(var j:int = 0; j < action.frameNum; j ++)
					{
						var url:String = action.urlPath + "\\" + GlobalCore.avatarName + "_" + action.name + "_" + (i+1)+ "_" + NumberTool.upperZero(j+1) + ".png";
						Resource.getInstance().appendMultiRes(action.name + i + "," + j, ResType.IMG, url);
					}
				}
				GlobalCore.totleLine += action.lineNum;
				Resource.getInstance().startLoad(onActionLoaded);
				//
			}
			else
			{
				loadSpriteAllOk();
			}
			
		}
		
		/**
		 * 一个动作加载完成 
		 */		
		private function onActionLoaded():void
		{
			Alert.showLog(_actionList[_totalCount].name+"  加载完成..");
			_totalCount ++;
			trace(_totalCount)
			analyzeAction();
		}
		
		/**
		 * 所有帧加载完成 
		 */		
		private function loadSpriteAllOk():void
		{
			_spriteDic = Resource.getInstance().resList;
			_preWidth	= _spriteDic[_actionList[0].name + "0,0"].width;
			_preHeight 	= _spriteDic[_actionList[0].name + "0,0"].height;
			
			_spriteWidth	= _preWidth;
			_spriteHeight	= _preHeight;
			
			GlobalCore.spritePreH 	= _preHeight;
			GlobalCore.spritePreW 	= _preWidth;
			GlobalCore.spriteDic 	= _spriteDic;
			GlobalCore.actions = _actionList;
			
			AppFacade.getInstance().sendNotification(MainNotification.TO_SHOW_ACTION_SPRITE);
			Alert.hideLog();
		}
		
		
		
		/**
		 * 粘贴一个操蛋的图
		 */		
		private function stickFuckingSprites():void
		{
//			var frontDic:Dictionary 		= new Dictionary();
//			var backDic:Dictionary 			= new Dictionary();
//			var skillFrontDic:Dictionary 	= new Dictionary();
//			var skillBackDic:Dictionary 	= new Dictionary();
			
//			var frontCount:int 		= 0;
//			var backCount:int 		= 0;
//			var skillFrontCount:int = 0;
//			var skillBackCount:int 	= 0;
			
//			var bmd:BitmapData;
			
			for each(var action:ActionVO in _actionList)
			{
				var frontDic:Dictionary = new Dictionary();
				for(var i:int = 0; i < action.frameNum; i ++)
				{
					if(i < int(action.frameNum/2))
					{
						frontDic["0"+","+i] = Resource.getInstance().resList[action.name + 0 + "," + i];
					}
					else
					{
						frontDic["1"+","+int(i - (action.frameNum/2))] = Resource.getInstance().resList[action.name + 0 + "," + i];
					}
					
				}
				action.frontBmd = stickOneFuckingBmd(frontDic,2,action.frameNum/2);
				
				if(action.lineNum == 2)
				{
					var backDic:Dictionary = new Dictionary();
					for(i = 0; i < action.frameNum; i ++)
					{
						if(i < int(action.frameNum/2))
						{
							backDic["0"+","+i] = Resource.getInstance().resList[action.name + 1 + "," + i];
						}
						else
						{
							backDic["1"+","+int(i - (action.frameNum/2))] = Resource.getInstance().resList[action.name + 1 + "," + i];
						}
					}
					action.backBmd = stickOneFuckingBmd(backDic,2,action.frameNum/2);
				}
				//
			}
			
			var file:File = _rootFile.resolvePath("..");
			var fileStream:FileStream = new FileStream();
			var ba:ByteArray;
			trace(file.nativePath)
			
			for each(action in _actionList)
			{
				fileStream.open(file.resolvePath(GlobalCore.avatarName + "_"+action.name+"Front.png"), FileMode.WRITE);
				ba = PNGEncoder.encode(action.frontBmd);
				fileStream.writeBytes(ba, 0, ba.length);
				fileStream.close();
				
				if(action.lineNum == 2)
				{
					fileStream.open(file.resolvePath(GlobalCore.avatarName + "_"+action.name+"Back.png"), FileMode.WRITE);
					ba = PNGEncoder.encode(action.backBmd);
					fileStream.writeBytes(ba, 0, ba.length);
					fileStream.close();
				}
			}
			
//			for each(var action:ActionVO in _actionList)
//			{
//				if(action.name != "skill01" && action.name != "skill02")
//				{
//					
//					for(var i:int = 0; i < action.lineNum; i ++)
//					{
//						for(var j:int = 0; j < action.frameNum; j ++)
//						{
//							bmd = Resource.getInstance().resList[action.name + i + "," + j];
//							if(i == 0)
//							{
//								frontDic[frontCount + "," + j] = bmd;
//							}
//							else
//							{
//								backDic[backCount + "," + j] = bmd;
//							}
//						}
//					}
//					frontCount ++;
//					if(action.lineNum == 2) backCount ++;
//				}
//				else
//				{
//					
//					for(i = 0; i < action.lineNum; i ++)
//					{
//						for(j = 0; j < action.frameNum; j ++)
//						{
//							bmd = Resource.getInstance().resList[action.name + i + "," + j];
//							if(i == 0)
//							{
//								skillFrontDic[skillFrontCount + "," + j] = bmd;
//							}
//							else
//							{
//								skillBackDic[skillBackCount + "," + j] = bmd;
//								
//							}
//						}
//					}
//					skillFrontCount ++;
//					if(action.lineNum == 2) skillBackCount ++;
//				}
//			}
//			
//			if(backCount == 0) _isHaveBack = false;
//			else _isHaveBack = true;
//			
//			var front:BitmapData = stickOneFuckingBmd(frontDic, frontCount, 10);
//			
//			if(_isHaveBack)
//				var back:BitmapData = stickOneFuckingBmd(backDic, backCount, 10);
//			
//			var skillFront:BitmapData = stickOneFuckingBmd(skillFrontDic, skillFrontCount, 16);
//			if(_isHaveBack)
//				var skillBack:BitmapData = stickOneFuckingBmd(skillBackDic, skillBackCount, 16);
//			
//			_fucking1 = PNGEncoder.encode(front);
//			if(_isHaveBack)
//				_fucking2 = PNGEncoder.encode(back);
//			_fucking3 = PNGEncoder.encode(skillFront);
//			if(_isHaveBack)
//				_fucking4 = PNGEncoder.encode(skillBack);
//			
//			var file:File = new File();
//			file.addEventListener(Event.SELECT, findFuckingPath);
//			file.browseForDirectory("保存路径");
			
		}
		
		/**
		 * 找到操蛋的路径
		 * @param evt 
		 */		
		private function findFuckingPath(evt:Event):void
		{
			var file:File = evt.target as File;
			
			var fileStream:FileStream = new FileStream();
			fileStream.open(file.resolvePath(GlobalCore.avatarName + "_FightFront.png"), FileMode.WRITE);
			fileStream.writeBytes(_fucking1, 0, _fucking1.length);
			fileStream.close();
			
			if(_isHaveBack)
			{
				fileStream.open(file.resolvePath(GlobalCore.avatarName + "_FightBack.png"), FileMode.WRITE);
				fileStream.writeBytes(_fucking2, 0, _fucking2.length);
				fileStream.close();
			}
			
			fileStream.open(file.resolvePath(GlobalCore.avatarName + "_SkillFront.png"), FileMode.WRITE);
			fileStream.writeBytes(_fucking3, 0, _fucking3.length);
			fileStream.close();
			
			if(_isHaveBack)
			{
				fileStream.open(file.resolvePath(GlobalCore.avatarName + "_SkillBack.png"), FileMode.WRITE);
				fileStream.writeBytes(_fucking4, 0, _fucking4.length);
				fileStream.close();
			}
		}
		
		/**
		 * 粘贴一张操蛋的png
		 * @param dic
		 * @param line
		 * @param frame
		 * @return  
		 */		
		private function stickOneFuckingBmd(dic:Dictionary, line:int, frame:int):BitmapData
		{
			trace(_spriteWidth * frame, _spriteHeight * line);
			var bmd:BitmapData = new BitmapData(_spriteWidth * frame, _spriteHeight * line, true, 0x00000000);
			for(var i:int = 0; i < line; i ++)
			{
				for(var j:int = 0; j < frame; j ++)
				{
					var srcBmd:BitmapData = dic[i+","+j];
					var newBmd:BitmapData = new BitmapData(_spriteWidth, _spriteHeight,true,0x00000000);
					
					//宽度变化造成的位图位移量
					var sizeOffX:int = (GlobalCore.spritePreW - _spriteWidth)/2;
					var sizeOffY:int = (GlobalCore.spritePreW - _spriteHeight)/2;
					
					newBmd.copyPixels(srcBmd, new Rectangle(sizeOffX - _offsetX, sizeOffY - _offsetY, _spriteWidth, _spriteHeight),
						new Point(0, 0)); //单张帧的切割
					
					if(bmd == null)//第一张图
						bmd = newBmd;
					else 
						bmd.copyPixels(newBmd, newBmd.rect, 
							new Point(j*_spriteWidth, i *_spriteHeight), null, null, true);
				}
				//
			}
			return bmd;
		}
		
		//
	}
}

class Singleton {}